using IQIGame.Onigao.Game;
using IQIGame.Onigao.GamePlay;
using System.Collections.Generic;

namespace IQIGame.Onigao.Logic
{
    /// <summary>
    /// 增加buff层数
    /// 参数组1：1：buff目标：（1.玩家，2.所有队员，3.队长，4：实体）2：buff cid，3：增加层数，4：实体tag(仅参数1位4时有效)
    /// </summary>
    public class ExecAddBuffStack : BaseServiceExecution
    {
        public override void Execute(LevelRegion region, LevelPlayer player)
        {
            var config = _config as ExecParamAddBuffStack;
            LevelBuffHostType hostType = (LevelBuffHostType)config.hostType;
            int buffCid = config.buffCid;
            int addStack = config.addStack;
            int tagOrMcid = 0;
            if (hostType == LevelBuffHostType.Entity)
            {
                if (!config.tagOrMcid.TryGetValue(triggerEntity, out tagOrMcid))
                {
                    LogicLog.LogError("修改buff堆叠层数出错，参数1为实体，但无法获取到tagOrMcid.");
                    return;
                }
            }
            if ((hostType == LevelBuffHostType.Player || hostType == LevelBuffHostType.AllHeroes || hostType == LevelBuffHostType.SingleHero) && player == null)
            {
                LogicLog.LogError("修改buff堆叠层数出错，player == null。buff目标为玩家，队伍，英雄时，必须由玩家主动触发服务。");
                return;
            }
            if (buffCid == 0)
            {
                LogicLog.LogError($"修改buff堆叠层数出错，buffCid非法：{buffCid}");
                return;
            }
            if (addStack == 0)
            {
                LogicLog.LogError($"修改buff堆叠层数出错，addStack非法：{addStack}");
                return;
            }
            if (tagOrMcid == 0 && triggerEntity == null)
            {
                LogicLog.LogError($"修改buff堆叠层数出错，仅由实体触发的服务可支持tag==0。");
                return;
            }
            List<BaseLevelFunctionHost> hosts = ListPool<BaseLevelFunctionHost>.Get();
            {
                List<LevelBuffChangeParam> changes = ListPool<LevelBuffChangeParam>.Get();
                {
                    region.GetBuffHost(hostType, player, tagOrMcid, triggerEntity, hosts);
                    for (int i = 0; i < hosts.Count; i++)
                    {
                        BaseLevelFunctionHost host = hosts[i];
                        bool isSuccess = host.AddBuffStack(buffCid, addStack, out LevelNormalBuff buff);
                        if (isSuccess)
                        {
                            LevelBuffChangeParam param = new LevelBuffChangeParam(hostType, host,
                                LevelBuffOperationType.AddStack, buff, 0);
                            changes.Add(param);
                        }
                    }
                    if (changes.Count > 0)
                    {
                        region.NotifyBuffChange(changes);
                    }
                    ListPool<LevelBuffChangeParam>.Put(changes);
                }
                ListPool<BaseLevelFunctionHost>.Put(hosts);
            }
        }
    }
}
